package cn.lyyb2001.blog.controller;

import cn.hutool.core.util.StrUtil;
import cn.lyyb2001.blog.entity.Tag;
import cn.lyyb2001.blog.service.ITagService;
import cn.lyyb2001.common.model.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * @author daiyb2
 * @Title: CategoriesController
 * @Description:
 * @date 2021/11/21 8:04
 **/
@RestController
@RequestMapping("/tags")
public class TagController {
    @Autowired
    private ITagService tagService;

    @GetMapping
    public Result<IPage<Tag>> list() {
        IPage<Tag> page = new Page<>();
        page.setRecords(tagService.list());
        page.setTotal(tagService.count());
        return Result.success(page);
    }

    @GetMapping("/list")
    public Result<IPage<Tag>> list(Page<Tag> page,
                       @RequestParam(required = false) String tagName) {
        IPage<Tag> result = tagService.page(page,
                new LambdaQueryWrapper<Tag>()
                        .like(StrUtil.isNotBlank(tagName), Tag::getTagName, tagName));
        return Result.success(result);
    }

    @GetMapping("/{id}")
    public Result<Tag> detail(@PathVariable String id) {
        Tag tag = tagService.getById(id);
        return Result.success(tag);
    }

    @PostMapping
    public Result add(@RequestBody Tag tag) {
        boolean status = tagService.save(tag);
        return Result.judge(status);
    }

    @PutMapping(value = "/{id}")
    public Result update(
            @PathVariable String id,
            @RequestBody Tag tag) {
        boolean status = tagService.updateById(tag);
        return Result.judge(status);
    }

    @DeleteMapping("/{ids}")
    public Result<Boolean> delete(@PathVariable("ids") String ids) {
        boolean status = tagService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.judge(status);
    }
}
